package cn.ztr.ymcc.interceptor;

import cn.ztr.ymcc.config.ExcludeProperties;
import cn.ztr.ymcc.jwt.JwtUtils;
import cn.ztr.ymcc.jwt.PayLoadData;
import cn.ztr.ymcc.jwt.Payload;
import cn.ztr.ymcc.jwt.RsaUtils;
import cn.ztr.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 拦截器
 */
//@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
    @Autowired
    private ExcludeProperties excludeProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            //0 放行路径
            RequestPath path = exchange.getRequest().getPath();
            if (excludeProperties.isExcluded(path.value()) )
                return chain.filter(exchange);
            //1 检查是否有token
            List<String> tokens = exchange.getRequest().getHeaders().get("jwtToken");
            if (tokens!=null&&!tokens.isEmpty()){
                //2 含有token 检查是否存在用户信息
                String token = tokens.get(0);
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
                Payload<PayLoadData> payload = JwtUtils.getInfoFromToken(token, publicKey, PayLoadData.class);
                if (payload!=null&&payload.getUserInfo().getLoginInfo()!=null){
                    //3.1 存在用户信息,放行
                    return chain.filter(exchange);
                }
            }

            //3.2 未登录,拦截
            DataBuffer buffer = null;
            //响应对象
            ServerHttpResponse response = exchange.getResponse();

            //设置完成相应，不会继续执行后面的filter
            //response.setComplete();
            response.getHeaders().set("content-type","application/json;charset=UTF-8");
            JsonResult jsonResult = JsonResult.error("noLogin");
            byte[] bytes = JSON.toJSONBytes(jsonResult);//阿里巴巴的json
            DataBuffer wrapper = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(wrapper));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
